package com.yanqu.road.server.manager.suoyao;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.suoyao.SuoYaoNotice;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.server.CrossBaseServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.utils.date.DateHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SuoYaoMgr extends TempMgr {

    private static Map<Integer, SuoYaoActivity> activityMap;

    @Override
    public boolean reloadData() throws Exception {
        synchronized (this) {
            if (activityMap == null) {
                activityMap = new ConcurrentHashMap<>();
            }
            // 获取活动
            String nowTimeStr = DateHelper.getCurrentDateTimeString();
            List<Integer> activityTypeList = new ArrayList<>();
            activityTypeList.add(eActivityType.SuoYaoActivity.getValue());
            Map<Integer, ActivityInfo> activityInfoMap = ActivityBussiness.getOpenCrossRankActivityInfoMapByCrossServerId(activityTypeList, nowTimeStr, CrossBaseServer.getInstance().getServerId());
            // 重新加载数据
            for (ActivityInfo activityInfo : activityInfoMap.values()) {
                if (!activityMap.containsKey(activityInfo.getActivityId())) {
                    getSuoYaoActivity(activityInfo.getActivityId());
                }
            }
        }
        return true;
    }

    public static synchronized SuoYaoActivity getSuoYaoActivity(int activityId) {
        if (activityMap.get(activityId) == null) {
            // 读配置 获取活动信息 保证有活动信息
            ActivityInfo activityInfo = ActivityBussiness.getActivityInfoByActivityId(activityId);
            if (activityInfo == null) {
                return null;
            }
            SuoYaoActivity activity = new SuoYaoActivity(activityInfo);
            activityMap.put(activityId, activity);
        }
        return activityMap.get(activityId);
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        if (activityMap != null) {
            for (SuoYaoActivity activity : activityMap.values()) {
                activity.save();
            }
        }
        return true;
    }

    public static void reloadConfig(int activityId) {
        if (activityMap.containsKey(activityId)) {
            activityMap.get(activityId).reloadConfig();
        }
    }

    public static void repair(int activityId) {
        if (activityMap.containsKey(activityId)) {
            activityMap.get(activityId).repair();
        }
    }
}
